<template>
  <breadCrumb ref="breadcrumb" :item="item"></breadCrumb>
  <div class="common-wrapped">
    <div class="common-content">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="账号详情" name="first">
          <div class="account-info-wrapped">
            <span>用户头像：</span>
            <div class="account-info-content">
              <!-- action 是上传头像的接口 -->
              <el-upload class="avatar-uploader" action="http://127.0.0.1:3007/user/uploadAvatar"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                :headers="headers">
                <img v-if="userStore.imageUrl" :src="userStore.imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>用户账号：</span>
            <div class="account-info-content">
              <el-input v-model="userData.account" disabled></el-input>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>用户密码：</span>
            <div class="account-info-content">
              <el-button type="primary" @click="openChangePW">修改密码</el-button>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>用户姓名：</span>
            <div class="account-info-content">
              <el-input v-model="userData.name"></el-input>
            </div>
            <div class="account-save-button">
              <el-button type="primary" @click="goUpdateName">保存</el-button>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>用户性别：</span>
            <div class="account-info-content">
              <el-select v-model="userData.sex">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>

            </div>
            <div class="account-save-button">
              <el-button type="primary" @click="goUpdateSex">保存</el-button>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>用户身份：</span>
            <div class="account-info-content">
              <el-input v-model="userData.identity" disabled></el-input>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>用户部门：</span>
            <div class="account-info-content">
              <el-input v-model="userData.department" disabled></el-input>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>用户邮箱：</span>
            <div class="account-info-content">
              <el-input v-model="userData.email"></el-input>
            </div>
            <div class="account-save-button">
              <el-button type="primary" @click="goUpdateEmail">保存</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="公司信息" name="second">
          <div class="account-info-wrapped">
            <span>公司名称</span>
            <div class="account-info-content">
              <el-input v-model="companyName"></el-input>
            </div>
            <div class="account-save-button">
              <el-button type="primary" @click="goUpdateCompanyName">编辑公司名称</el-button>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>公司介绍</span>
            <div class="account-info-content">
              <el-button type="primary" @click="openEditor(1)">编辑公司介绍</el-button>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>公司架构</span>
            <div class="account-info-content">
              <el-button type="primary" @click="openEditor(2)">编辑公司架构</el-button>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>公司战略</span>
            <div class="account-info-content">
              <el-button type="primary" @click="openEditor(3)">编辑公司战略</el-button>
            </div>
          </div>
          <div class="account-info-wrapped">
            <span>公司高层</span>
            <div class="account-info-content">
              <el-button type="primary" @click="openEditor(4)">编辑公司高层</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="首页管理" name="third">
          <div class="home-wrapped">
            <!-- 提示 -->
            <div class="tips">
              <span>
                提示: 点击图片框进行切换首页轮播图
              </span>
            </div>
            <!-- 轮播图 -->
            <div class="swiper-wrapped" v-for="(item, index) in swiperData">
              <div class="swiper-name">轮播图{{ index + 1 }}:&nbsp;&nbsp;</div>
              <el-upload class="avatar-uploader" action="http://127.0.0.1:3007/set/uploadSwiper" :show-file-list="false"
                :on-success="handleSwiperSuccess" :before-upload="beforeAvatarUpload" :data='item' :headers="headers">
                <template #trigger>
                  <img v-if="imageUrl[index]" :src="imageUrl[index]" class="swiper" />
                  <img v-else src="../../assets/masaike.png" alt="">
                </template>
              </el-upload>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="其他设置" name="fourth">
          <div class="other-set">
            <div class="department-set">
              <span>部门设置</span>
              <el-tag class="mx-1" closable v-for="item in departmentList" @close="deleteDepartment(item)">{{ item
                }}</el-tag>
              <el-input v-if="inputVisible" v-model="departmentInputValue" size="small"
                @keyup.enter="addDepartment(departmentInputValue)" @blur="addDepartment(departmentInputValue)" />
              <el-button v-else @click="inputVisible = true">
                + 添加部门
              </el-button>
            </div>
            <div class="product-set">
              <span>产品设置</span>
              <el-tag class="mx-1" closable v-for="item in productList" @close="deleteProduct(item)">{{ item
                }}</el-tag>
              <el-input v-if="inputVisiblepro" v-model="productInputValue" size="small"
                @keyup.enter="addProduct(productInputValue)" @blur="addProduct(productInputValue)" />
              <el-button v-else @click="inputVisiblepro = true">
                + 添加部门
              </el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
  <!-- 修改密码弹窗 -->
  <changePW ref="changePWRef"></changePW>
  <!-- 富文本编辑器 -->
  <editor ref="editorRef"></editor>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue"
import breadCrumb from "../../components/breadCrumb.vue"
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { ElInput, UploadProps } from 'element-plus'
import { useUserInfo } from '../../store/userinfo'
import { bindAccountAPI, getUserInfoAPI } from '../../api/userinfo'
import changePW from './components/changePW.vue'
import { updateNameAPI, updateEmailAPI, updateSexAPI } from '../../api/userinfo'
import editor from './components/editor.vue'
import { bus } from "../../utils/mitt"
import { getCompanyNameAPI, updateCompanyNameAPI, getAllSwiperAPI } from '../../api/setting'
import { Store } from "pinia"
import { tracking } from '../../utils/operate'
import { getCompanyDepartment, setCompanyDepartment, getCompanyProduct, setCompanyProduct } from '../../api/setting'


const inputVisible = ref(false)
const departmentInputValue = ref()

const inputVisiblepro = ref(false)
const productInputValue = ref()

const userStore = useUserInfo() as Store<"userinfo", { imageUrl: string; name: string; sex: string; department: string; identity: string; account: string; email: string; }, {}, { userInfo }>



const breadcrumb = ref()
const item = ref({
  first: '系统设置'
})
const activeName = ref('first')


// 从localstorage获取name
const name = JSON.parse(localStorage.getItem('userinfo') as string).name

const token = localStorage.getItem('token')
const headers = {
  'Authorization': token
}

// 头像上传成功的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  if (response.status == 0) {

    userStore.$patch({
      imageUrl: response.url
    })
    ElMessage({
      message: '上传头像成功',
      type: 'success',
    }),
      (async () => {
        const res = await bindAccountAPI({ account: userStore.account, url: userStore.imageUrl, onlyId: response.onlyId })
        console.log(res)



        tracking("系统设置", "修改头像", name, "低级")

      })()
  } else {
    ElMessage({
      message: '上传头像失败',
      type: 'error',
    })
  }

}
// 头像上传之前的函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('头像必须是 JPG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('头像必须小于 10 MB!')
    return false
  }
  return true
}

// 账号
interface userData {
  account: number | null,
  name: string,
  sex: string,
  identity: string,
  department: string,
  email: string
}

const userData: userData = reactive({
  account: null,
  name: '',
  sex: '',
  identity: '',
  department: '',
  email: ''
})

// 获取用户信息
const getUserInfo = async () => {
  const res = await getUserInfoAPI(localStorage.getItem('id'))
  userData.account = res.data.data.account
  userData.name = res.data.data.name
  userData.sex = res.data.data.sex
  userData.identity = res.data.data.identity
  userData.department = res.data.data.department
  userData.email = res.data.data.email
  userStore.userInfo(localStorage.getItem('id'))
}
onMounted(() => {
  getUserInfo()
})

// 打开修改密码弹窗
const changePWRef = ref()
const openChangePW = () => {
  changePWRef.value.openDialog()
}

// 修改姓名
const goUpdateName = async () => {
  const res = await updateNameAPI({
    id: localStorage.getItem('id'),
    name: userData.name
  })
  if (res.data.status == 0) {
    ElMessage({
      message: '修改姓名成功',
      type: 'success',
    })
    tracking("系统设置", "修改姓名", name, "低级")
    userStore.userInfo(localStorage.getItem('id'))
  } else {
    ElMessage({
      message: '修改姓名失败',
      type: 'error',
    })
  }
}

// 修改性别
const goUpdateSex = async () => {
  const res = await updateSexAPI({
    id: localStorage.getItem('id'),
    sex: userData.sex
  })
  if (res.data.status == 0) {
    ElMessage({
      message: '修改性别成功',
      type: 'success',
    })
    tracking("系统设置", "修改性别", name, "低级")
    userStore.userInfo(localStorage.getItem('id'))
  } else {
    ElMessage({
      message: '修改性别失败',
      type: 'error',
    })
  }
}

// 修改邮箱
const goUpdateEmail = async () => {
  const res = await updateEmailAPI({
    id: localStorage.getItem('id'),
    email: userData.email
  })
  if (res.data.status == 0) {
    ElMessage({
      message: '修改邮箱成功',
      type: 'success',
    })
    tracking("系统设置", "修改性别", name, "低级")
    userStore.userInfo(localStorage.getItem('id'))
  } else {
    ElMessage({
      message: '修改邮箱失败',
      type: 'error',
    })
  }
}

// 获取公司名称
const companyName = ref()
const getCompanyName = async () => {
  const res = await getCompanyNameAPI()
  companyName.value = res.data.data
}
getCompanyName()

// 修改公司名称
const goUpdateCompanyName = async () => {
  const res = await updateCompanyNameAPI(companyName.value)
  if (res.data.status == 0) {
    ElMessage({
      message: '修改公司名称成功',
      type: 'success',
    })
    tracking("系统设置", "修改公司名称", name, "高级")
  }

}


const editorRef = ref()

// 打开富文本编辑器
const openEditor = (id: number) => {
  // 第一个参数是 标记, 第二个是参数是 id
  bus.emit('editorTitle', id)
  editorRef.value.open()
}

const swiperData = [{
  name: 'swiper1'
}, {
  name: 'swiper2'
}, {
  name: 'swiper3'
}, {
  name: 'swiper4'
}, {
  name: 'swiper5'
}, {
  name: 'swiper6'
}]

const imageUrl = ref([])

// 上传轮播图成功
const handleSwiperSuccess: UploadProps['onSuccess'] = (response,
  uploadFile) => {
  console.log(response)
  tracking("系统设置", "修改首页轮播图", name, "中级")
  if (response.status == 0) {
    getAllSwiper()
  }
}

// 获取所有轮播图
const getAllSwiper = async () => {
  const res = await getAllSwiperAPI()
  let swiperList = res.data.data

  const swiperUrlList = swiperList.map((item) => {
    return item.set_value
  })
  imageUrl.value = swiperUrlList
}

getAllSwiper()


// 获取部门列表
const departmentList = ref<string[]>([]);
const getDepartmentList = async () => {
  const res = await getCompanyDepartment()
  departmentList.value = JSON.parse(res.data.data) as string[];
}
getDepartmentList()


// 增加部门
const addDepartment = async (val) => {
  if (val !== undefined) {
    let newDep = departmentList.value
    newDep.push(val)
    inputVisible.value = false
    const res = await setCompanyDepartment(JSON.stringify(newDep))
    getDepartmentList()
    departmentInputValue.value = ''
  } else {
    inputVisible.value = false
  }
}

// 删除部门
const deleteDepartment = async (item) => {
  let newDep = departmentList.value
  newDep.splice(newDep.indexOf(item), 1)
  const res = await setCompanyDepartment(JSON.stringify(newDep))
  getDepartmentList()
}

// 获取产品列表
const productList = ref<string[]>([]);
const getProductList = async () => {
  const res = await getCompanyProduct()
  productList.value = JSON.parse(res.data.data) as string[];
}
getProductList()


// 增加产品
const addProduct = async (val) => {
  if (val !== undefined) {
    let newPro = productList.value
    newPro.push(val)
    inputVisiblepro.value = false
    const res = await setCompanyProduct(JSON.stringify(newPro))
    getProductList()
    productInputValue.value = ''
  } else {
    inputVisiblepro.value = false
  }
}

// 删除产品
const deleteProduct = async (item) => {
  let newPro = productList.value
  newPro.splice(newPro.indexOf(item), 1)
  const res = await setCompanyProduct(JSON.stringify(newPro))
  getProductList()
}

</script>

<style lang="scss" scoped>
// 外壳
.common-wrapped {
  padding: 8px;
  background: #f5f5f5;
  // 计算 减去了头部还有面包屑 + 2X8=16边距
  height: calc(100vh - 101px);

  // 内容
  .common-content {
    padding: 0 10px;
    height: 100%;
    background: #fff;

    // 账号信息外壳
    .account-info-wrapped {
      display: flex;
      align-items: center;
      padding-left: 50px;
      margin-bottom: 24px;
      font-size: 14px;

      // 账号信息内容
      .account-info-content {
        margin-left: 24px;
        margin-right: 16px;
      }

      // 按钮
      .account-save-button {
        margin-left: 16px;
      }
    }

    // 首页管理外壳
    .home-wrapped {
      padding-left: 50px;
      display: flex;
      flex-direction: column;

      // 提示
      .tips {
        display: flex;
        align-items: center;
        margin-bottom: 8px;

        span {
          font-size: 14px;
          color: silver;
        }
      }

      // 轮播图
      .swiper-wrapped {
        display: flex;
        margin-bottom: 16px;

        // 轮播图名字
        .swiper-name {
          font-size: 14px;
          margin-bottom: 24px;
        }

        .swiper {
          width: 336px;
          height: 100px;

        }
      }
    }
  }
}



// 其他设置
.other-set {
  padding-left: 0px;
  font-size: 14px;

  .department-set {
    margin-bottom: 24px;

    span {
      margin-right: 24px;
    }
  }

  .product-set {

    span {
      margin-right: 24px;
    }
  }

}

// 标签页
.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

// 上传头像
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

// 输入框的长度
:deep(.el-input) {
  width: 240px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-select {
  width: 240px;
}
</style>
